/**
 * @author: zouye<yzyngz@foxmail.com>
 * @date: 2021-12-19 18:12:38
 * @copyright: zouye<yzyngz@foxmail.com>
 */
package com.yeah.study.easyoffice.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.htcs.screen.baseinfo.quotation.entity.QuotationDetail;
import com.htcs.screen.baseinfo.quotation.entity.QuotationItem;
import com.yeah.study.easyoffice.service.ExcelService;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;

/**
 *
 */
@RestController
@RequestMapping("/excel/")
public class ExcelController {

	@Autowired
	private ExcelService excelService;
	
	@RequestMapping("export")
	public void exportExcel(HttpServletResponse response) throws Exception {
		excelService.useEasyPoiMergeExcel(response);
	}
	
	/**
	 * 从 Excel 模板导出，支持表达式
	 * @author zouye
	 * @param req
	 * @param response
	 * @throws Exception
	 */
    @RequestMapping("downloadTest")
    public void downloadTest(HttpServletRequest req, HttpServletResponse response)
            throws Exception {
        excelService.setDownloadHeader(response, "测试模板表达式.xlsx");
        
        TemplateExportParams params = new TemplateExportParams("报价单导出模板_表达式语法.xlsx");
        Map<String, Object> sheetMap = new HashMap<>();
        
        // 测试多条item
        List<Map<String, Object>> itemList = new ArrayList<>();
        List<String> itemKeys = Arrays.asList("itemName", "itemQuantity", "itemUnitPrice");
        Map<String, Object> itemMap = new HashMap<>();
        for (int t = 0; t < 4; t++) {
            for (int i = 0; i < itemKeys.size(); i++) {
                itemMap.put(itemKeys.get(i), i + "");
            }
            itemList.add(itemMap);
        }
        
        List<Map<String, Object>> rowMapList = new ArrayList<>();
        Map<String, Object> rowMap = new HashMap<>();
        List<String> keys = Arrays.asList("index", "deliveryDept", "useDept", "name", "specification", "quantity", "standard", "skin", "grade", "sampleEncapsulation", "price");
        for (int i = 0; i < itemList.size(); i++) {
            // 插入要合并单元格的内容
            for (int k = 0; k < keys.size(); k++) {
                rowMap.put(keys.get(k), k + "");
            }
            
            Map<String, Object> item = itemList.get(i);
            for (String key: item.keySet()) {
                rowMap.put(key, item.get(key));
            }
            
            rowMapList.add(rowMap);
        }
        
        sheetMap.put("rowMapList", rowMapList);
        sheetMap.put("sumQuantity", 1000);
        sheetMap.put("sumPrice", 10200);
        
        Workbook workbook = ExcelExportUtil.exportExcel(params, sheetMap);
        PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 7, 0,1,2,3,4,5,6,7,8,9,13,14);
        
        OutputStream outStream = null;
        try {
            outStream = response.getOutputStream();
            workbook.write(outStream);
        } catch (Exception e) {
            throw e;
        } finally {
            if (outStream != null) {
                outStream.flush();
                outStream.close();
            }
        }
    }
    
    /**
     * 从模板导出 Excel 的数据格式转换
     * @author zouye
     * @param exportList
     * @return
     * @throws Exception
     */
    private Map<String, Object> getMapForExport(List<QuotationDetail> exportList) throws Exception {
        List<Map<String, Object>> rowMapList = new ArrayList<>();
        List<String> keys = Arrays.asList("index", "deliveryDept", "useDept", "name", "specification", "quantity", "standard", "skin", "grade", "sampleEncapsulation", "price");
        //List<String> itemKeys = Arrays.asList("itemName", "itemQuantity", "itemUnitPrice");
        Map<String, Object> sheetMap = new HashMap<>();
        Integer sumQuantity = 0;
        Float sumPrice = 0F;
        for (QuotationDetail e: exportList) {
            Map<String, Object> rowMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(e.getItemList())) {
                for (QuotationItem item: e.getItemList()) {
                    // 插入要被合并单元格的内容
                    for (int k = 0; k < keys.size(); k++) {
                        String field = keys.get(k);
                        if (field.equals("skin")) {
                            rowMap.put(field, e.getSkin() == 1 ? "是" : "否");
                        } else if (field.equals("price")) {
                            rowMap.put(field, e.getPrice());
                        } else {
                            rowMap.put(field, BeanUtils.getProperty(e, keys.get(k)));
                        }
                    }
                    
                    rowMap.put("itemName", item.getName());
                    rowMap.put("itemQuantity", item.getQuantity());
                    rowMap.put("itemUnitPrice", item.getUnitPrice());
                    
                    rowMapList.add(rowMap);
                }
            } else {
                for (int k = 0; k < keys.size(); k++) {
                    String field = keys.get(k);
                    if (field.equals("skin")) {
                        rowMap.put(field, e.getSkin() == 1 ? "是" : "否");
                    } else if (field.equals("price")) {
                        rowMap.put(field, e.getPrice());
                    } else {
                        rowMap.put(field, BeanUtils.getProperty(e, keys.get(k)));
                    }
                }
                
                rowMapList.add(rowMap);
            }
            
            
            if (e.getPrice() != null) {
                sumPrice = sumPrice + e.getPrice();
            }
            
            if (e.getQuantity() != null) {
                sumQuantity = sumQuantity + e.getQuantity();
            }
        }
        
        sheetMap.put("rowMapList", rowMapList);
        sheetMap.put("sumQuantity", sumQuantity);
        sheetMap.put("sumPrice", sumPrice);
        
        return sheetMap;
    }
}
